/**
 * 
 */
package ca.utoronto.cms.cscc85.project4.teamrf;

import ca.utoronto.cms.cscc85.project4.teamrf.R;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

/**
 * this class displays the recipe selected
 *
 */
public class ViewRecipeActivity extends Activity implements OnCheckedChangeListener {
	/** Called when the activity is first created. */
	public ToggleButton countdownToggle; //sets up the timer
    public TimePicker countdownTimer;
    private Handler countdownHandler = new Handler();
    
    /**
     * Creates the interface layout by the xml file
     */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewrecipe);
    
        // get bundle from intent call
        Bundle bundle = getIntent().getExtras();
        
        // initiate all text fields
        TextView nameText = (TextView) findViewById(R.id.viewNameText);
        nameText.setText(bundle.getString("name"));
        TextView timeText = (TextView) findViewById(R.id.viewTimeText);
        timeText.setText("Preparation Time: " + bundle.getInt("time") + " mins.\n");
        TextView ingredientsText = (TextView) findViewById(R.id.viewIngredientsText);
        ingredientsText.setText(bundle.getString("ingredients") + "\n");
        TextView directionsText = (TextView) findViewById(R.id.viewDirectionsText);
        directionsText.setText(bundle.getString("directions") + "\n\n");
        
        // initiate countdown picker
        countdownToggle = (ToggleButton) findViewById(R.id.countdownToggle);
        countdownToggle.setOnCheckedChangeListener(this);
        countdownTimer = (TimePicker) findViewById(R.id.countdownTimer);
        countdownTimer.setIs24HourView(true);
        countdownTimer.setCurrentHour(0);
        countdownTimer.setCurrentMinute(0);

    }
	/**
	 * Turns the timer on and off
	 */
	public void onCheckedChanged(CompoundButton arg0, boolean checked) {
        // if the toggle is on, remove callbacks from previous timers and start a new one
		if (checked) {
			if (countdownTimer.getCurrentHour() > 0 || countdownTimer.getCurrentMinute() > 0) {
				countdownHandler.removeCallbacks(updateTimer);
				countdownHandler.postDelayed(updateTimer, 100);
			} else {
				countdownToggle.setChecked(false);
			}	
		} else {
        	// if the toggle is off, turn off the timer
        	countdownHandler.removeCallbacks(updateTimer);
        }
	}
	/**
	 * performs the countdown
	 */
	private Runnable updateTimer = new Runnable() {
		public void run() {
			// get current time from timer
			int minute = countdownTimer.getCurrentHour();
			int second = countdownTimer.getCurrentMinute();
					    
			//update time
			
			second -= 1;
			if (second == 0 && minute == 0) {
				// fire alarm and cancel timer and toggle button off
				countdownHandler.removeCallbacks(updateTimer);
				countdownToggle.setChecked(false);

				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(new long[] {0, 300, 300, 300, 300, 300}, -1);
				
				// get audio alert
				Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
		    	if(alert == null){
		    		// no alarm default, try notification
		    		alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		    		if(alert == null){ 
		    			// no notification default, try ringtone
		    			alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);               
		    		}
		    	}
		    	
		    	// try to play a sound
			    MediaPlayer player = new MediaPlayer();
			    try {
			    	player.setDataSource(getApplicationContext(), alert);
			    	final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
			    	if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
			            player.setAudioStreamType(AudioManager.STREAM_ALARM);
			            player.prepare();
			            player.start();
			        }
			    } catch (Exception e) {
			    	e.printStackTrace();
			    }
			    
				Toast toast = Toast.makeText(getApplicationContext(),
                        "Timer Done", Toast.LENGTH_SHORT);
                toast.show();
			} else if (second == -1) {
				minute -= 1;
				second = 59;
			}

			// update widget
		    countdownTimer.setCurrentHour(minute);
		    countdownTimer.setCurrentMinute(second);
		    
		    // if timer is still valid, set to fire in 1 second
		    if (countdownToggle.isChecked())
		    	countdownHandler.postAtTime(this, SystemClock.uptimeMillis() + 1000);

		   }
		};
    
}
